import React, {PureComponent, Fragment} from 'react';
import moment from 'moment';
import {connect} from 'dva';
import {
  Button,
  Icon,
  Modal,
  Form,
  message,
  Table,
} from 'antd';
import RewardCheck from './Rewardcheck'
import debounce from 'lodash/debounce'
import {ellipsis,afterCloseModal} from '@/utils/utils';
import Check from './check'
import LevelCheck from './Levelcheck'
import BuildModalTitle from '@/components/BuildModalTitle';
const FormItem = Form.Item;
const { confirm } = Modal;
@connect()
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
    };
  }


  componentDidMount = async()=> {
    this.changeTableY()
    const {dispatch} = this.props;
    const {
      [this.props.model_name]: {pageLoaded, scrollData,},
    } = this.props;
    console.log('pageLoaded', pageLoaded)
    const table = document.querySelector('.ant-table-body')
    if (pageLoaded) {
      setTimeout(function () {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0)

    } else {
      const {
        [this.props.model_name]: {searchParams},
      } = this.props;
      console.log('searchParams', searchParams)
      dispatch({
        type:`${this.props.model_name}/fetchReward`
      })
      dispatch({
        type: `${this.props.model_name}/fetch`,
        payload: {},
        callback: ()=> {
          const {dispatch} = this.props;
          dispatch({
            type: `${this.props.model_name}/changeLoaded`,
          })
        }
      });
    }

    window.addEventListener('resize', this.resize)
    table.addEventListener('scroll', debounce(this.scroll, 150))
  }
  scroll = (e)=> {
    const {dispatch} = this.props;
    dispatch({
      type: `${this.props.model_name}/changeScroll`,
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop
      },
    })
  }
  resize = ()=> {
    this.changeTableY()
  }
  changeTableY = ()=> {
    this.setState({
      tableY: document.querySelector('.table-pagination').getBoundingClientRect().top -
      document.querySelector('.custom-small-table').getBoundingClientRect().top - 50
    })
  }

  componentWillUnmount() {
    console.log('componentWillUnmount')
    window.removeEventListener('resize', this.resize)
    const table = document.querySelector('.ant-table-body')
    table.removeEventListener('scroll', debounce(this.scroll, 300))
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values)
    const that = this;
    const {dispatch} = this.props;
    dispatch({
      type: `${this.props.model_name}/fetch`,
      payload: {
        ...values,
      },
      callback: function () {
        console.log('handleSearch callback')
        if (cb) cb()
      }
    });
  }
  handleEdit = ()=> {
    const formValues = this.EditUser.props.form.getFieldsValue();
    console.log('formValues', formValues)
    const that = this;
    this.props.dispatch({
      type: `${this.props.model_name}/edit`,
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
      },
      callback: function () {
        message.success('修改成功')
        that.setState({
          editModal: false,
        });
        console.log('changeCommission1')
        that.props.dispatch({
          type: `${that.props.model_name}/changeCommission`,
          payload:{
            id: that.state.editRecord.id,
            level: that.state.editRecord.level,
            initial_commission:formValues.initial_commission,
            promotion_commission:formValues.promotion_commission,
            promotion_conditions:formValues.promotion_conditions,
          }

        })
      }
    });
  }
  handleEditLevel=()=>{
    const formValues = this.editLevel.props.form.getFieldsValue();
    console.log('formValues', formValues)
    const that = this;
    this.props.dispatch({
      type: `${this.props.model_name}/editLevel`,
      payload: {
        ...formValues,
        level:formValues.level.key,
      },
      callback: function () {
        message.success('修改成功')
        that.setState({
          editLevelModal: false,

        });
        console.log('changeCommission1')
        that.props.dispatch({
          type: `${that.props.model_name}/changeLevelCommission`,
          payload:{
            level:formValues.level.key,
            initial_commission:formValues.initial_commission,
            promotion_commission:formValues.promotion_commission,
            promotion_conditions:formValues.promotion_conditions

          }

        })
      }
    });
  }
  handleChangeStatus = (id,status)=> {
    const that = this;
    this.props.dispatch({
      type: `${that.props.model_name}/edit`,
      payload: {
        status,
        id
      },
      callback: function () {
        message.success('修改成功')
        console.log('handleChangeStatus')
        that.props.dispatch({
          type: `${that.props.model_name}/handleChangeStatus`,
          payload:{
            status,
            id
          }

        })
      }
    });
  }
  handleEditReward=()=>{
    const formValues = this.editReward.props.form.getFieldsValue();
    console.log('formValues', formValues)
    const that = this;
    this.props.dispatch({
      type: `${that.props.model_name}/editReward`,
      payload: {
        ...formValues,
        start_timestamp:Date.parse(formValues.start_timestamp)/1000,
        end_timestamp:Date.parse(formValues.end_timestamp)/1000,
      },
      callback: function () {
        message.success('修改奖励佣金成功')
        that.setState({
          rewardModal: false,

        });
        that.props.dispatch({
          type: `${that.props.model_name}/fetchReward`,
          payload:{
          }

        })
      }
    });
  }
  renderSimpleForm() {
    const {
      [this.props.model_name]: {reward_commissions},
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem >
          <Button icon="branches" className="btn-green"  type="primary" onClick={
            ()=> {
              this.setState({
                editLevelModal: true
              })
            }
          }>
            层级佣金设置
          </Button>
          <Button   icon="money-collect" type="primary" onClick={
            ()=> {
              this.setState({
                rewardModal: true
              })
            }
          }>
            奖励佣金设置
          </Button>
          <span className={"reward"}>当前奖励佣金 <span className='red' style={{marginRight:'10px'}}>{reward_commissions.reward_commission}元</span>
            时间 <span className='red'>{moment(reward_commissions.start_timestamp*1000).format("YYYY-MM-DD HH:mm:ss")}</span>至
            <span className='red'>{moment(reward_commissions.end_timestamp*1000).format("YYYY-MM-DD HH:mm:ss")}</span>
          </span>
        </FormItem>

      </Form>
    );
  }
  render() {
    const {
      [this.props.model_name]: {data, loading, meta, expandedRowKeys, selectedRowKeys,reward_commissions},
    } = this.props;
    const {
      form: {getFieldDecorator},
    } = this.props;
    const columns = [
      {
        title: '头像/昵称(点击箭头展开)',
        dataIndex: 'avatar_url',
        width: 200,
        fixed:'left',
        render: (val, record)=> {
          return <span style={{marginLeft: record.downline_count === 0 ? '16px' : 0}}>
            <img className="table-avatar" src={record.avatar_url}
                 alt=""/>{ ellipsis(record.nickname, 200 - 12 - 16 - 35 - 20-15 * (record.level - 1))}

          </span>
        }
      },
      {
        title: '状态',
        dataIndex: 'status',
        width: 80,
        render(val) {
          let type="", color="", text="";
          switch (val){
            case -1:
            case '-1':
              type="close-circle", color="#eb2f96", text="禁用";
              break;
            case 1:
            case '1':
              type="check-circle", color="#52c41a", text="启用";
              break;
            default:
              break
          }
          return  <Fragment> <Icon type={type} theme="twoTone"  className="table-icon" twoToneColor={color}/>{text}</Fragment>
        },
      },
      {
        title: '层级',
        dataIndex: 'level',
        width: 60,
        render: (val, record)=> {
          return ellipsis('层级' + record.level, 100)
        }
      },
      {
        title: '下线数量',
        dataIndex: 'downline_count',
        width: 80,
        render: (val, record)=> {
          return ellipsis(val, 80)
        }
      },
      {
        title: '总收入',
        dataIndex: 'total_revenue',
        width: 80,
        render: (val, record)=> {
          return <span className="money">￥{val}元</span>
        }
      },
      {
        title: '预计收入',
        dataIndex: 'forecast_revenue',
        width: 80,
        render: (val, record)=> {
          return <span className="money">￥{val}元</span>
        }
      },
      {
        title: '成功申请数量',
        dataIndex: 'successful_application_count',
        width: 100,
        render: (val, record)=> {
          return ellipsis(val, 100)
        }
      }, {
        title: '预计申请数量',
        dataIndex: 'forecast_application_count',
        width: 100,
        render: (val, record)=> {
          return ellipsis(val, 100)
        }
      },
      {
        title: '当前佣金',
        dataIndex: 'current_commission',
        width: 100,
        render: (val, record)=> {
          return <span className="money">￥{val}元</span>
        }
      },
      {
        title: '初始佣金',
        dataIndex: 'initial_commission',
        width: 100,
        render: (val, record)=> {
          return <span className="money">￥{val}元</span>
        }
      },
      {
        title: '晋升后佣金',
        dataIndex: 'promotion_commission',
        width: 120,
        render: (val, record)=> {
          return <span className="money">￥{val}元</span>
        }
      },
      {
        title: '晋升条件',
        dataIndex: 'promotion_conditions',
        width: 100,
        render: (val, record)=> {
          return ellipsis(val + '人', 120)
        }
      },
      {
        title: '姓名',
        dataIndex: 'name',
        width: 90,
        render: (val, record)=> {
          return ellipsis(record.name, 90)
        }
      },
      {
        title: '手机',
        dataIndex: 'mobile',
        render: (val, record)=> {
          return ellipsis(val, 100)
        }
      },
      {
        title: '操作',
        width: 195,
        fixed: 'right',
        render: (val, record, index) => {
          return <Fragment>
            {(record.level === 1|| record.level === 2)?  <Button style={{marginRight: '8px'}} type="primary" icon='edit' size="small" onClick={(e)=> {
              // e.stopPropagation()
              this.setState({
                editRecord: record,
                editModal: true
              })
            }
            }>修改初始佣金</Button>
            : ''}
            <Button type={record.status==1?'danger':'primary'} className={record.status==1?'':'btn-green'}   size="small" onClick={(e)=> {
              e.stopPropagation()
              confirm({
                title: `确定要${record.status==1?'禁用':'启用'}"${record.nickname}"吗?`,
                content: '请谨慎操作！',
                okText: '确定',
                okType: 'danger',
                cancelText: '取消',
                maskClosable:true,
                onOk() {
                  that.handleChangeStatus(record.id,record.status==1?-1:1)
                },
                onCancel() {
                  console.log('Cancel');
                },
              });
            }
            }>{record.status==1?'禁用':'启用'}</Button>
          </Fragment>
        }

      },
    ];
    const rowSelection = {
      columnWidth: 40,
      selectedRowKeys,
      columnTitle: ' ',
      onChange: (selectedRowKeys) => {
        this.props.dispatch({
          type: `${this.props.model_name}/changeSelectRow`,
          payload: selectedRowKeys,
        })
      },
    };
    const that = this

    function CustomExpandIcon(props) {
      let text;
      if (props.expanded) {
        text = props.record.downline_count === 0 ? '' : 'caret-down';
      } else {
        text = props.record.downline_count === 0 ? '' : 'caret-up';
      }
      return (
        <Icon type={text} style={{color: 'blue', cursor: 'pointer', fontSize: '16px', top: '2px', position: 'relative'}}
              onClick={e => {
                e.stopPropagation();
                e.persist();
                if (props.record.children) {
                  props.onExpand(props.record, e)
                } else {
                  that.handleSearch({
                    parent_id: props.record.id
                  }, function () {
                    props.onExpand(props.record, e)
                  })
                }
              }}/>
      );
    }

    return <div className="custom-card">
      <div className="table-title">分销商</div>
      <div className="table-page">
        <div className="table-condition">
          {this.renderSimpleForm()}
        </div>
        <Table
          style={{color: '#fff'}}
          className="custom-small-table"
          loading={loading}
          rowKey={'id'}
          dataSource={data}
          columns={columns}
          pagination={false}
          size="small"
          indentSize={20}
          expandedRowKeys={expandedRowKeys}
          onExpand={(expanded, record)=> {
            this.props.dispatch({
              type: `${this.props.model_name}/changeExpandedRowKeys`,
              payload: {
                id:record.id,
                expanded:expanded
              },
            })
          }}
          defaultExpandAllRows={true}
          expandIcon={CustomExpandIcon}
          scroll={{x: 1800, y: this.state.tableY}}
          rowSelection={rowSelection}
          onRow={(record) => ({
            onClick: () => {
              this.props.dispatch({
                type: `${this.props.model_name}/selectRow`,
                payload: record,
              })
            },
          })}
        />

      </div>
      <div className="table-pagination">
      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.editModal}  modalClass={'editModal'}  title={'修改佣金'} />}
        destroyOnClose
        visible={this.state.editModal}
        afterClose={ ()=>{
          afterCloseModal() //destroyOnClose需要
        }}
        centered
        className={'editModal'}
        onOk={this.handleEdit}
        onCancel={()=> {
          this.setState({editModal: false, editRecord: {}})
        }}
      >
        <Check editRecord={this.state.editRecord}
               wrappedComponentRef={(inst) => this.EditUser = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.editLevelModal}  modalClass={'editLevelModal'}  title={'层级佣金设置'} />}
        visible={this.state.editLevelModal}
        centered
        className={'editLevelModal'}
        onOk={this.handleEditLevel}
        afterClose={ ()=>{
          afterCloseModal() //destroyOnClose需要
        }}
        destroyOnClose
        onCancel={()=> {
          this.setState({editLevelModal: false})
        }}
      >
        <LevelCheck
              project_id={this.props.project_id}
               wrappedComponentRef={(inst) => this.editLevel = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.rewardModal}  modalClass={'rewardModal'}  title={'奖励佣金设置'} />}
        visible={this.state.rewardModal}
        centered
        className={'rewardModal'}
        afterClose={ ()=>{
          afterCloseModal() //destroyOnClose需要
        }}
        destroyOnClose
        onOk={this.handleEditReward}
        onCancel={()=> {
          this.setState({rewardModal: false})
        }}
      >
        <RewardCheck

          reward_commissions={reward_commissions}
          wrappedComponentRef={(inst) => this.editReward = inst}/>

      </Modal>
    </div>
  }
}

export default BasicList;
